package com.fanketly.funacg2.data.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.HistoryModel
import com.fanketly.funacg2.data.repo.HistoryRepo


class HistoryPagingSource(
    private val repo: HistoryRepo,
) : PagingSource<Int, HistoryModel>() {
    override fun getRefreshKey(state: PagingState<Int, HistoryModel>): Int? {
        return state.anchorPosition?.let {
            state.closestPageToPosition(it)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(it)?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, HistoryModel> {
        val page = params.key ?: 1 //当前页，默认第一页
        val pageSize = params.loadSize //每页数据条数
        val repository = kotlin.runCatching {
            repo.getAll(
                page,
                pageSize,
            )
        }.getOrElse {
            return LoadResult.Error(it)
        }
        val previousPage = if (page > 1) page - 1 else null //前一页
        val nextPage = if (repository.isNotEmpty()) page + 1 else null //下一页
        Log.d(TAG, "page=$page size=$pageSize")
        return LoadResult.Page(repository, previousPage, nextPage)
    }

}